package com.titaniume.java;

import org.junit.Test;

import java.io.*;

/**
 * @program: JavaSenior
 * @description:
 *
 *
 * 处理流之二： 转换流的使用
 *
 * 1.装换流:属于字符流
 *  InputStreamReader：将一个字节的输入流转换为字符的输入流
 *  OutputStreamWriter：将一个字符的输出流转换为字节的输出流
 *
 * 2.作用： 提供字节与字符流的转换
 *
 *
 * 3.  解码 字节、字节数组、  ---> 字符数组、字符串
 *     编码： 字符数组、字符串  ---> 字节、字节数组
 *
 *
 * 4.字符集
 *
 *
 *
 *
 *
 *
 * @author: renfei.huang
 * @create: 2021-10-17 21:33
 */
public class InputStreamReaderTest {




    //解码 读入操作
    //字节流操作 ，字符流输出
    //InputStreamReader的使用，实现了字节的输入流到字符的输入流的转换
    @Test
    public void  test1() throws IOException {


        FileInputStream fileInputStream = null;
        InputStreamReader  inputStreamReader =   null;

        try {
             fileInputStream = new FileInputStream(new File("dbcp.txt"));

            //使用系统默认的字符集
//        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            //参数2指明了字符集，具体使用哪个字符集 取决于文件dbcp.txt保存时使用的字符集
              inputStreamReader = new InputStreamReader(fileInputStream,"utf-8");

            char [] cbuf = new char[50];
            int len;
            while ((len = inputStreamReader.read(cbuf))!= -1){
                String str = new String(cbuf, 0, len);
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if(fileInputStream!= null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(inputStreamReader!= null){
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    /*
    *
    * 综合使用InputStreamReader 、OutputStreamWriter
    *
    * */
    @Test
    public  void test2() throws Exception{

        //1.造文件，造流
        File file1 = new File("dbcp.txt");
        File file2 = new File("dbcp_gbk.txt");

        FileInputStream fileInputStream = new FileInputStream(file1);
        FileOutputStream fileOutputStream = new FileOutputStream(file2);

        //读入 解码
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"utf-8");
        //写出 编码
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,"gbk");


        //2.读写过程
        char [] cbuf = new char[20];
        int len;
        while ((len = inputStreamReader.read(cbuf))!=-1){
            outputStreamWriter.write(cbuf,0,len);
        }


        //3.资源关闭
        inputStreamReader.close();
        outputStreamWriter.close();

    }

}
